from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from database.database import get_db
from core.base.api_mode import ApiResponse, api_success
from core.token_manager import get_current_user
from modules.system.params.user_params import UserQuery
from modules.system.schemas.user_schemas import (
    UserCreate, UserUpdate, PasswordChangeRequest
)
from modules.system.vos.user_vo import UserResponse, UserListResponse
from modules.system.services.user_service import UserService
from modules.system.vos.auth_vo import MeResponse
from core.pagination import DependsPagination

router = APIRouter()


@router.post("/create", response_model=ApiResponse[UserResponse], summary="创建用户")
async def create_user(
    payload: UserCreate, 
    db: AsyncSession = Depends(get_db)
):
    user = await UserService.create_user(db, payload)
    return api_success(UserResponse.model_validate(user), msg="创建成功")


@router.post(
    "/list", 
    response_model=ApiResponse[UserListResponse], 
    summary="获取用户列表",
    dependencies=[DependsPagination])
async def list_users(
    query_params: UserQuery,
    db: AsyncSession = Depends(get_db)
):
    result = await UserService.get_users_with_pagination(db, query_params)
    return api_success(data=result, msg="获取成功")


@router.put("/{user_id}", response_model=ApiResponse[UserResponse], summary="更新用户")
async def update_user(user_id: int, payload: UserUpdate, db: AsyncSession = Depends(get_db)):
    user = await UserService.update_user(db, user_id, payload)
    return api_success(data=user, msg="更新成功")


@router.delete("/{user_id}", response_model=ApiResponse[dict], summary="删除用户")
async def delete_user(user_id: int, db: AsyncSession = Depends(get_db)):
    await UserService.delete_user(db, user_id)
    return api_success({"message": f"用户ID {user_id} 删除成功"}, msg="删除成功")


@router.post("/{user_id}/password", response_model=ApiResponse[dict], summary="修改密码")
async def change_password(
    user_id: int, 
    payload: PasswordChangeRequest, 
    db: AsyncSession = Depends(get_db), 
):
    await UserService.change_password(db, user_id, payload.old_password, payload.new_password)
    return api_success({"message": "密码修改成功"}, msg="修改成功")


@router.get("/me", response_model=ApiResponse[MeResponse], summary="获取当前用户信息")
async def me(
    current_user=Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
):
    user_id = current_user.get("uid")
    user_data = await UserService.get_user_profile_by_id(db, user_id) if user_id is not None else None
    if user_data:
        username = user_data.get("username") or current_user.get("sub")
        return api_success(data={**user_data, "username": username}, msg="获取成功")

    # 回退到 token 信息
    fallback = {
        "id": current_user.get("uid"),
        "username": current_user.get("sub"),
        "roles": current_user.get("roles", []),
    }
    return api_success(MeResponse.model_validate(fallback), msg="获取成功")